package daytrader.framework;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import daytrader.common.*;
import daytrader.lib.*;

/* 
 * This class is used to simulate the ticks of 
 * stock exchange market
 */
public class Tick {
	private static int tick;
	private Thread tickThread;
	// the read/write lock to synchronize among threads
	private static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

	
	public static int readTick(){
		rwl.readLock().lock();
		int t = Tick.tick;
		rwl.readLock().unlock();
		return t;
	}
	
	public static void resetTick(){
		rwl.writeLock().lock();
		Tick.tick = 0;
		rwl.writeLock().unlock();
	}
	
	public static void incrementTick(){
		rwl.writeLock().lock();
		Tick.tick++;
		rwl.writeLock().unlock();
	}
	
	public static int waitNextTick(int last_tick){
		while (true) {
			int t = Tick.readTick();
			if (t != last_tick && t != 0) return t;
				
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void Start(){
		TickThread p = new TickThread();
		this.tickThread = new Thread(p);
		this.tickThread.start();
	}
	
	@SuppressWarnings("deprecation")
	public void stop(){
		this.tickThread.stop();
	}
	
	/*
	 * This class implement the ticking thread
	 */
	class TickThread implements Runnable {

		public void run() {
			while (true) {
				if (ExchangeTime.IsMarketOpen()) {
					Tick.incrementTick();
				}
				else {
					Tick.resetTick();
				}
				
				try {
					// tick increase every 5 seconds
					Thread.sleep(Constants.DEFAULT_TICK_LENGTH);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
